package com.caiheng.api.controller.estate;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.estate.*;
import com.caiheng.api.entity.platform.Parameter;
import com.caiheng.api.entity.platform.PlatformPay;
import com.caiheng.api.entity.platform.SplitAccount;
import com.caiheng.api.entity.platform.SplitAccountRecord;
import com.caiheng.api.entity.product.ProductCart;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.exception.TransactionalException;
import com.caiheng.api.pay.nongshang.NSQuery;
import com.caiheng.api.rabbitmq.RabbitConfig;
import com.caiheng.api.rabbitmq.RabbitMqSender;
import com.caiheng.api.service.estate.*;
import com.caiheng.api.service.platfom.*;
import com.caiheng.api.service.sys.SysConfigService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.DateUtil;
import com.caiheng.api.util.GsonResultBean;
import com.caiheng.api.util.StringUtil;
import com.caiheng.api.util.Tools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  小区相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/property")//url:模块/资源/{}/细分
public class PropertyController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private EstateService estateService;
    @Resource
    private EstateRoomService estateRoomService;
    @Resource
    private PropertyService propertyService;
    @Resource
    private PropertyFeeOrderService propertyFeeOrderService;
    @Resource
    private PropertyFeeOrderInfoService propertyFeeOrderInfoService;
    @Resource
    private SysConfigService sysConfigService;
    @Resource
    private ParameterService parameterService;
    @Resource
    private PlatformPayService platformPayService;
    @Resource
    private WxPayTransactionService wxPayTransactionService;
    @Resource
    private PropertyRegisterService propertyRegisterService;
    @Resource
    private SplitAccountService splitAccountService;
    @Resource
    private SplitAccountRecordService splitAccountRecordService;

    @Resource
    private RabbitConfig rabbitConfig;
    private RabbitMqSender rabbitMqSender;

    /**
     * 测试
     * @return
     */
    @PostMapping(value = "/test")
    public JSONObject test(@RequestBody String requestParam, HttpServletRequest request){
        JSONObject ret = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0L;


//            PlatformPay platformPay = platformPayService.getById(2);
//            NSQuery.queryOrder("37UT120240409162401",platformPay);

            PropertyFeeOrder feeOrder = propertyFeeOrderService.findById(50);
            if(feeOrder != null){
                Estate estate = estateService.getById(feeOrder.getEstateId());
                if(estate != null){
                    //开启赠送积分功能
                    if(estate.getIsOpenIntegral() != null && estate.getIsOpenIntegral() == 1){
                        Date beginDate = estate.getOpenBeginDate();
                        Date endDate = estate.getOpenEndDate();
                        if(beginDate.getTime() < new Date().getTime() && new Date().getTime() < endDate.getTime()) {
                            String configValue = sysConfigService.selectConfigByKey("module.integral_count");
                            double totalMoney = feeOrder.getPayMoney().doubleValue();
                            long totalIntegral = (long) totalMoney * Integer.parseInt(configValue) * estate.getIntegralMultiple();
                            SplitAccount account = splitAccountService.getAccountByUserId(feeOrder.getUserId(), 4, feeOrder.getUserId());
                            if (account != null) {
                                account.setIntegralCount(account.getIntegralCount() + totalIntegral);
                                boolean bl1 = splitAccountService.updateById(account);

                                SplitAccountRecord accountRecord = new SplitAccountRecord();
                                accountRecord.setUserId(feeOrder.getUserId());
                                accountRecord.setAccountId(account.getId());
                                accountRecord.setCreateTime(new Date());
                                accountRecord.setFromType(16);
                                accountRecord.setRemark("交物业费获取积分");
                                //1 - 进账  0 - 出账
                                accountRecord.setInOrOut(1);
                                accountRecord.setSplitMoney(new BigDecimal(totalIntegral));
                                boolean bl = splitAccountRecordService.save(accountRecord);
                            }
                        }
                    }
                }
            }

            //查询1天之前 取消掉的订单
//            QueryWrapper<PropertyFeeOrder> qw = new QueryWrapper<>();
//            qw.eq("state", 5);
//            qw.eq("is_del",0);
//            qw.le("create_time", DateUtil.getBeforeDayDate(-1) );
//            List<PropertyFeeOrder> orderList = propertyFeeOrderService.list(qw);
//            if (CollUtil.isNotEmpty(orderList)) {
//                for (PropertyFeeOrder feeOrder : orderList) {
////                        feeOrder.setIsDel(1);
////                        feeOrderService.updateById(feeOrder);
//                }
//            }

            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功","单价："),true,false);

        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 添加物业缴费订单
     * @param
     * @throws Exception
     */
    @PostMapping(value="/addOrder")
    public JSONObject addOrder(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "property/addOrder 接收的参数： "+requestParam);
            System.out.println("property/addOrder 接收的参数： " +requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;
            double room_areas = jsonRequest.containsKey("room_areas") ? jsonRequest.getDouble("room_areas") : 0d;
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : "";
            String room_no = jsonRequest.containsKey("room_no") ? jsonRequest.getStr("room_no") : "";
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "wxmini";


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(user.getEstateId() == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定社区"),true,true);
            }

            Estate estate = estateService.findById(estate_id);
            if(estate == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该社区不存在"),true,true);
            }

            if(estate.getState() == 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该社区已暂停服务"),true,true);
            }

            Parameter parameter = parameterService.getParameterById(1);
            PlatformPay platformPay = platformPayService.getAccountByPropertyId(estate.getPropertyId());

            PropertyFeeOrder feeOrder = new PropertyFeeOrder();
            feeOrder.setUserId(user_id);
            feeOrder.setEstateId(estate_id);
            feeOrder.setPropertyId(estate.getPropertyId());
            feeOrder.setRoomAreas(room_areas+"");
            feeOrder.setState(0);
            feeOrder.setRoomNo(room_no);
            feeOrder.setIsOpenReceipt(0);
            feeOrder.setPlatform(platform);
            String orderNo = estate.getId() + DateUtil.getSdfffTimes();
            if(platformPay!=null){
                orderNo = platformPay.getSysCode() + estate.getId() + DateUtil.getSdfffTimes();
                feeOrder.setPayPlatformId(platformPay.getId());
            }
            feeOrder.setOrderNo(orderNo);
            feeOrder.setOutTradeNo(orderNo);
            feeOrder.setPayPlatform(parameter.getWyfPayPlatform());

            double totalPrice = 0;//room_areas * estate.getSinglePrice().doubleValue();

            feeOrder.setWyfFee(new BigDecimal(totalPrice));
            feeOrder.setTotalMoney(new BigDecimal(totalPrice));

            feeOrder.setDkRate(0);
            double diKouPrice = 0;
            String diKouRate = sysConfigService.selectConfigByKey("sys.integral_rate");
            if(StrUtil.isNotEmpty(diKouRate)){
                feeOrder.setDkRate(Integer.parseInt(diKouRate));
                double d  = Double.parseDouble(diKouRate);
                diKouPrice = Double.parseDouble(String.format("%.2f",d));
            }

            double payMoney = totalPrice - diKouPrice;
            feeOrder.setCreateTime(new Date());
            feeOrder.setPayMoney(new BigDecimal(payMoney));
            feeOrder.setBeginTime(new Date());
            feeOrder.setEndTime(new Date());
            feeOrder.setPhoneNum(phone_num);
            try{
                long order_id = propertyFeeOrderService.addOrder(feeOrder, user);
                if(order_id > 0){
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",order_id),true,false);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"失败",estate),true,true);
                }
            }catch (Exception e){
                e.printStackTrace();
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"失败",estate),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     *  根据选择的 物业模板数据 生成物业费订单
     * @param
     * @throws Exception
     */
    @PostMapping(value="/addOrderByTemplate")
    public JSONObject addOrderByTemplate(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "property/addOrderByTemplate 接收的参数： "+requestParam);
            System.out.println("property/addOrderByTemplate 接收的参数： " +requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String begin_month = jsonRequest.containsKey("begin_month") ? jsonRequest.getStr("begin_month") : "";
            String end_month = jsonRequest.containsKey("end_month") ? jsonRequest.getStr("end_month") : "";
            int room_id = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;
            String checkIds = jsonRequest.containsKey("checkIds") ? jsonRequest.getStr("checkIds") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            Parameter parameter = parameterService.getParameterById(1);
            if(parameter != null){
                if(parameter.getIsOpenWyf() == 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"收费功能暂未开通，请联系客服咨询具体开通时间"),true,true);
                }
            }


            EstateRoom estateRoom = estateRoomService.findById(room_id);
            if(estateRoom == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该房屋不存在"),true,true);
            }

            try{
                long order_id = propertyFeeOrderService.addOrderByTemplate(user,estateRoom,checkIds,begin_month,end_month);
                if(order_id > 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"提交成功", order_id),true,false);
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败"),true,true);
                }
            }catch (Exception e){
                e.printStackTrace();
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     *  根据选择的 物业模板数据 生成物业费订单
     * @param
     * @throws Exception
     */
    @PostMapping(value="/addOrderByTemplate1")
    public JSONObject addOrderByTemplate1(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "property/addOrderByTemplate1 接收的参数： "+requestParam);
            System.out.println("property/addOrderByTemplate1 接收的参数： " +requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String begin_month = jsonRequest.containsKey("begin_month") ? jsonRequest.getStr("begin_month") : "";
            String end_month = jsonRequest.containsKey("end_month") ? jsonRequest.getStr("end_month") : "";
            int room_id = jsonRequest.containsKey("room_id") ? jsonRequest.getInt("room_id") : 0;
            String chooseFee = jsonRequest.containsKey("chooseFee") ? jsonRequest.getStr("chooseFee") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }


            Parameter parameter = parameterService.getParameterById(1);
            if(parameter != null){
                if(parameter.getIsOpenWyf() == 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"收费功能暂未开通，请联系客服咨询具体开通时间"),true,true);
                }
            }


            EstateRoom estateRoom = estateRoomService.findById(room_id);
            if(estateRoom == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该房屋不存在"),true,true);
            }

            Estate estate = estateService.findById(estateRoom.getEstateId());
            if(estate != null){
                if(estate.getState() == 1){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"收费功能暂未开通，请联系客服咨询具体开通时间"),true,true);
                }
            }


            //每次生成订单的时候 先取消之前未支付的订单，防止出现支付混乱的情况
            //本来想先提示用户去修改，修改需要改动的地方很多，倒不如直接给取消掉重新生成
            QueryWrapper<PropertyFeeOrder> qwOrder = new QueryWrapper<>();
            qwOrder.eq("user_id", user_id);
            qwOrder.eq("room_id", room_id);
            Integer[] state = { 0, 1, 2, 3};
            qwOrder.in("state", Arrays.asList(state));
            long orderCount = propertyFeeOrderService.count(qwOrder);
            if(orderCount > 0){
                propertyFeeOrderService.update(Wrappers.<PropertyFeeOrder>lambdaUpdate()
                                .set(PropertyFeeOrder::getState,5)
                                .eq(PropertyFeeOrder::getUserId,user_id)
                                .eq(PropertyFeeOrder::getRoomId,room_id)
                                .in(PropertyFeeOrder::getState, Arrays.asList(state)));
            }



            try{
                long order_id = propertyFeeOrderService.addOrderByTemplate1(user,estateRoom,chooseFee,begin_month,end_month);
                if(order_id > 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"提交成功", order_id),true,false);
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败"),true,true);
                }
            }catch (Exception e){
                e.printStackTrace();
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 根据地址添加物业费订单申请
     * @param
     * @throws Exception
     */
    @PostMapping(value="/addOrderByAddress")
    public JSONObject addOrderByAddress(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "property/addOrderByAddress 接收的参数： "+requestParam);
            System.out.println("property/addOrderByAddress 接收的参数： " +requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;
            String estate_name = jsonRequest.containsKey("estate_name") ? jsonRequest.getStr("estate_name") : "";
            String real_name = jsonRequest.containsKey("real_name") ? jsonRequest.getStr("real_name") : "";
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : "";
            String room_no = jsonRequest.containsKey("room_no") ? jsonRequest.getStr("room_no") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            int[] state = {0, 1};

            QueryWrapper<PropertyFeeOrder> qw = new QueryWrapper<>();
            qw.select("id");
            qw.eq("user_id",user_id);
            //订单状态 0 - 未支付  1- 支付中 2 - 已支付 3 - 订单取消
            qw.in("state", Arrays.asList(state));
            long feeOrderCount = propertyFeeOrderService.count(qw);
            if(feeOrderCount > 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您有暂未支付的订单，请处理完成后在申请！"),true,true);
            }

            PropertyFeeOrder feeOrder = new PropertyFeeOrder();
            feeOrder.setUserId(user_id);
            feeOrder.setEstateId(estate_id);

            Estate estate = estateService.findById(estate_id);
            if(estate!=null){
                feeOrder.setEstateName(estate.getEstateName());
            }
            feeOrder.setPropertyId(user.getPropertyId());

            Property property = propertyService.findById(user.getPropertyId());
            if(property!=null){
                feeOrder.setPropertyName(property.getPropertyName());
            }

            feeOrder.setRoomAreas("0");
            feeOrder.setState(0);
            feeOrder.setRoomNo(estate_name + room_no);
            feeOrder.setNickName(user.getNickName());
            feeOrder.setRealName(real_name);
            String orderNo = "32WT" + user.getEstateId() + DateUtil.getSdfffTimes();
            feeOrder.setOrderNo(orderNo);
            feeOrder.setOutTradeNo(orderNo);

            Parameter parameter = parameterService.getParameterById(1);
            feeOrder.setPayPlatform(parameter.getWyfPayPlatform());
            PlatformPay platformPay = platformPayService.getAccountByPropertyId(estate.getPropertyId());
            if(platformPay!=null){
                feeOrder.setPayPlatformId(platformPay.getId());
            }

            double totalPrice = 0;
            feeOrder.setIsOpenReceipt(0);
            feeOrder.setWyfFee(new BigDecimal(totalPrice));
            feeOrder.setTotalMoney(new BigDecimal(totalPrice));
            feeOrder.setMonths(0);
            feeOrder.setDkRate(0);
            feeOrder.setCreateTime(new Date());
            feeOrder.setPayMoney(new BigDecimal(0));
            feeOrder.setPhoneNum(phone_num);
            try{
                long order_id = propertyFeeOrderService.addOrder(feeOrder, user);
                if(order_id > 0){
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"申请成功"),true,false);
                }else{
                    result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"申请失败"),true,true);
                }
            }catch (Exception e){
                e.printStackTrace();
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"申请失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 取消订单
     * @param
     * @throws Exception
     */
    @PostMapping(value="/cancelOrder")
    public JSONObject cancelOrder(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "property/cancelOrder 接收的参数： " + requestParam + "      " +  DateUtil.getTime());

            System.out.println("property/cancelOrder 接收的参数： " +requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            PropertyFeeOrder order = propertyFeeOrderService.findById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else if(order.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }

            //订单状态 0 - 交费申请 1 - 已生成交费清单  2 - 待支付  3- 支付中  4 - 已支付 5 - 订单取消
            if(order.getState() == 0 || order.getState() == 1 || order.getState() == 2 || order.getState() == 3){
                propertyFeeOrderService.updateOrderState(order,5);
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"订单取消成功!"),true,true);
            }else if(order.getState() == 5){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已取消"),true,true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不能取消"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

    /** 获取所有订单列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/order/list")
    public JSONObject getList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "property/order/list 接收的参数： "+requestParam);
            System.out.println("property/order/list 接收的参数： " +requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : -1;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            //订单状态 0 - 未支付  1 - 支付中  2 - 已支付
            List<PropertyFeeOrder> orders = propertyFeeOrderService.queryListByUserId(user_id,state,pageIndex,pageSize);
            map.put("orders",orders);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",orders.size(), map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     *  订单详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/order/detail")
    public JSONObject orderDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "property/order/detail 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            System.out.println("property/order/detail 接收的参数： " +requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            PropertyFeeOrder order = propertyFeeOrderService.findById(order_id);
            if(order!=null){
                String payMoney = StringUtil.yuanToCent(order.getPayMoney().toString());
                order.setPayMoneyFen(Integer.parseInt(payMoney));

                order.setBeginDate(DateUtil.getTimesStr(order.getBeginTime(),DateUtil.sdfMonth));
                order.setEndDate(DateUtil.getTimesStr(order.getEndTime(),DateUtil.sdfMonth));

                QueryWrapper<PropertyFeeOrderInfo> qw = new QueryWrapper<>();
                qw.eq("order_id",order.getId());
                List<PropertyFeeOrderInfo> orderInfos = propertyFeeOrderInfoService.list(qw);
                if(CollUtil.isNotEmpty(orderInfos)){
                    for (PropertyFeeOrderInfo orderInfo : orderInfos){
                        orderInfo.setBeginMonth(DateUtil.getTimesStr(orderInfo.getBeginDate(),DateUtil.sdfMonth));
                        orderInfo.setEndMonth(DateUtil.getTimesStr(orderInfo.getEndDate(),DateUtil.sdfMonth));
                    }
                }
                order.setOrderInfos(orderInfos);
            }


            Estate estate = estateService.findById(order.getEstateId());
            if(estate!=null){
                order.setEstateName(estate.getEstateName());
            }

            Map<String,Object> map = new HashMap<>();
            map.put("order",order);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  订单支付状态查询
     * @param
     * @throws Exception
     */
    @PostMapping(value="/order/query")
    public JSONObject orderQuery(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "property/order/query 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            System.out.println("property/order/query 接收的参数： " +requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;

//            User user = userService.findById(user_id);
//            if(user == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
//            }

            PropertyFeeOrder feeOrder = propertyFeeOrderService.findById(order_id);
            if(feeOrder == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单不存在"),true,true);
            }

            int ret = propertyFeeOrderService.queryOrder(feeOrder);
            if(ret > 0){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"查询失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  订单支付状态查询
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add/register")
    public JSONObject addRegister(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "property/add/register 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            System.out.println("property/add/register 接收的参数： " +requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String property_name = jsonRequest.containsKey("property_name") ? jsonRequest.getStr("property_name") : "";
            String estate_name = jsonRequest.containsKey("estate_name") ? jsonRequest.getStr("estate_name") : "";
            String leader_name = jsonRequest.containsKey("leader_name") ? jsonRequest.getStr("leader_name") : "";
            String leader_phone = jsonRequest.containsKey("leader_phone") ? jsonRequest.getStr("leader_phone") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            PropertyRegister register = new PropertyRegister();
            register.setUserId(user_id);
            register.setCreateTime(new Date());
            register.setPropertyName(property_name);
            register.setEstateName(estate_name);
            register.setLeaderName(leader_name);
            register.setLeaderPhone(leader_phone);
            boolean bl = propertyRegisterService.save(register);
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"提交成功，我们会尽快与您联系~"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }



}
